<?php
/*
+--------------------------------------------------------------------------
|   Anwsion [#RELEASE_VERSION#]
|   ========================================
|   by Tatfook Network Team
|   (c) 2011 - 2012 Anwsion Software
|   http://www.anwsion.com
|   ========================================
|   Support: zhengqiang@gmail.com
|   
+---------------------------------------------------------------------------
*/

class c_user_class extends AWS_CONTROLLER
{

	function get_permission_action()
	{
	
	}

	public function setup()
	{
		admin_session_class::check_admin_login($this->get_permission_action());
		$this->crumb("会员管理", "admin/user/");
	}

	public function index_action()
	{
		$this->list_action();
	}

	public function list_action()
	{
		if ($_POST['keyword'])
		{
			header('Location: ' . $_SERVER['REQUEST_URI'] . (preg_match('/\/$/', $_SERVER['REQUEST_URI']) ? '' : '__') . 'keyword-' . $_POST['keyword']);
		}
		
		$per_page = 15;
		
		$page_id = intval($_GET['page']);
		
		$page_id = ($page_id == 0) ? 1 : $page_id;
		
		$limit = ($page_id - 1) * $per_page . "," . $per_page;
		
		$keyword = $_GET['keyword'];
		
		$page_url = get_setting('base_url') . '/' . G_INDEX_SCRIPT . "/admin/user/list/";
		
		$m_keyword = AWS_APP::model()->quote($keyword);
		
		if ($keyword)
		{
			$user_list = $this->model('user_manage')->get_user_list(false, "user_name LIKE '%" . $m_keyword . "%' OR email LIKE '%" . $m_keyword . "%'", $limit);
			$totalnum = $this->model('user_manage')->get_user_list(true, "user_name LIKE '%" . $m_keyword . "%' OR email LIKE '%" . $m_keyword . "%'");
			$keyword_url .= "keyword-" . $keyword;
		}
		else
		{
			$user_list = $this->model('user_manage')->get_user_list(false, "", $limit);
			$totalnum = $this->model('user_manage')->get_user_list(true);
		}
		
		$this->model('pagination')->initialize(array(
			'base_url' => $page_url . $keyword_url, 
			'total_rows' => $totalnum, 
			'per_page' => $per_page, 
			'last_link' => '末页', 
			'first_link' => '首页', 
			'next_link' => '下一页 »', 
			'prev_link' => '« 上一页', 
			'anchor_class' => ' class="number"', 
			'cur_tag_open' => '<a class="number current">', 
			'cur_tag_close' => '</a>', 
			'direct_page' => TRUE
		));
		
		TPL::assign('pagination', $this->model('pagination')->create_links());
		TPL::assign('system_groups', $this->model('user_manage')->get_group('type = 0'));
		TPL::assign('keyword', $keyword);
		TPL::assign('list', $user_list);
		TPL::output('admin/user/list');
	}

	public function group_list_action()
	{
		$system_group = $this->model('user_manage')->get_group('type = 0');
		
		$mem_group = $this->model('user_manage')->get_group('type = 1');
		
		$this->crumb("用户组管理", "admin/user/group_list");
		
		TPL::assign('mem_group', $mem_group);
		TPL::assign('system_group', $system_group);
		TPL::output('admin/user/group_list');
	}

	public function group_save_ajax()
	{
		define('IN_AJAX', TRUE);
		
		if ($group_data = $_POST['group'])
		{
			foreach ($group_data as $key => $val)
			{
				if (empty($val['group_name']))
				{
					H::ajax_json_output(AWS_APP::RSM(null, "-1", "用户组名称不能为空"));
				}
				
				if ($val['reputation_factor'])
				{
					if(!is_numeric($val['reputation_factor']) || floatval($val['reputation_factor']) < 0)
					{
						H::ajax_json_output(AWS_APP::RSM(null, "-1", "威望系数必须为大于或等于0的数字"));
					}
					
					if(!is_numeric($val['reputation_lower']) || floatval($val['reputation_lower']) < 0 || !is_numeric($val['reputation_higer']) || floatval($val['reputation_higer']) < 0)
					{
						H::ajax_json_output(AWS_APP::RSM(null, "-1", "威望介于值必须为大于或等于0的数字"));
					}
					
					$val['reputation_factor'] = floatval($val['reputation_factor']);
				}
				
				$this->model('user_manage')->update_group('group_id = ' . $key, $val);
			}
		}
		
		if ($group_new = $_POST['group_new'])
		{
			foreach ($group_new['group_name'] as $key => $val)
			{
				if (trim($group_new['group_name'][$key]))
				{
					$this->model('user_manage')->add_group($group_new['group_name'][$key], $group_new['reputation_lower'][$key], $group_new['reputation_higer'][$key], $group_new['reputation_factor'][$key]);
				}
			}
		}
		
		if ($group_ids = $_POST['group_ids'])
		{
			foreach ($group_ids as $key => $val)
			{
				$group_info = $this->model('account')->get_group_by_id($val);
				
				if ($group_info['type'] == 1)
				{
					$this->model('user_manage')->remove_group($val);
				}
				else
				{
					H::ajax_json_output(AWS_APP::RSM(null, "-1", "系统用户组不可删除。"));
				}
			}
		}
		
		if ($group_new || $group_ids)
		{
			$rsm_array = array(
				'url' => get_js_url('?/admin/user/group_list/')
			);
		}
		
		H::ajax_json_output(AWS_APP::RSM($rsm_array, "1", "用户组更新成功"));
	}

	public function group_edit_action()
	{
		$group_id = intval($_GET['group_id']);
		
		$group = $this->model('account')->get_group_by_id($group_id);
		
		if (! $group)
		{
			H::redirect_msg('用户组不存在');
		}
		
		$this->crumb("用户组编辑", "admin/user/group_edit");
		
		TPL::assign('group', $group);
		TPL::assign('group_pms', $group['permission']);
		TPL::output('admin/user/group_edit');
	}

	/**
	 * 保存用户组编辑
	 */
	public function group_edit_process_action()
	{
		$group_id = intval($_GET['group_id']);
		
		$permission_array = array(
			'is_administortar', 
			'is_moderator', 
			'publish_question', 
			'edit_question', 
			'edit_topic', 
			'upload_attach', 
			'publish_url', 
			'human_valid', 
			'question_valid_hour', 
			'answer_valid_hour'
		);
		
		$group_setting = array();
		
		foreach ($permission_array as $permission)
		{
			$group_setting[$permission] = $_POST[$permission];
		}
		
		$retval = $this->model('user_manage')->update_group('group_id = ' . $group_id, array(
			'permission' => serialize($group_setting)
		));
		
		H::ajax_json_output(AWS_APP::RSM(null, "1", "用户组更新成功"));
	}

	/**
	 * 修改用户资料
	 * Enter description here ...
	 */
	public function edit_action()
	{
		$user_id = intval($_GET['uid']);
		
		$this->crumb("修改用户", "admin/user/edit/uid-" . $user_id);
		
		TPL::assign('system_group', $this->model('user_manage')->get_group('type = 0'));
		TPL::assign('user', $this->model('account')->get_users_by_uid($user_id));
		TPL::output("admin/user/edit");
	}

	/**
	 * 用户修改处理
	 * Enter description here ...
	 */
	public function user_save_ajax_action()
	{
		define('IN_AJAX', TRUE);
		
		$user_id = intval($_POST['uid']);
		
		if ($user_id)
		{
			unset($_POST['uid']);
			
			if ($user_id == 0)
			{
				H::ajax_json_output(AWS_APP::RSM(null, "-1", "系统错误，用户ID不能为空"));
			}
			
			$user_info = $this->model('account')->get_users_by_uid($user_id);
			
			if ($_POST['user_name'] != $user_info['user_name'] && $this->model('account')->get_users_by_username($_POST['user_name']))
			{
				H::ajax_json_output(AWS_APP::RSM(null, "-1", "用户名已存在。"));
			}
			
			$update_user = $this->model('user_manage')->format_user_field($_POST);
			
			if ($update_user['delete_avatar'])
			{
				$this->model('account')->delete_avatar($user_id);
				unset($update_user['delete_avatar']);
			}
			
			if ($this->user_info['group_id'] != '1')
			{
				unset($update_user['group_id']);
			}
			
			if (! empty($update_user['password']))
			{
				$this->model('account')->update_user_password_ingore_oldpassword($update_user['password'], $user_id, fetch_salt(4));
			}
			
			if ($user_info['group_id'] == 3 && $update_user['valid_email'] == 1)
			{
				$update_user['group_id'] = 4;
			}
			
			unset($update_user['password']);
			
			$this->model('account')->update_users_fields($update_user, $user_id);
			
			H::ajax_json_output(AWS_APP::RSM(null, "1", "用户资料修改成功"));
		}
		else
		{
			//检查用户名
			if (trim($_POST['user_name']) == '')
			{
				H::ajax_json_output(AWS_APP::RSM(null, - 1, "请输入用户名"));
			}
			
			if ($this->model('account')->check_username($_POST['user_name']))
			{
				H::ajax_json_output(AWS_APP::RSM(null, - 1, "用户名已经存在"));
			}
			
			if ($this->model('account')->check_email($_POST['email']))
			{
				H::ajax_json_output(AWS_APP::RSM(null, - 1, "E-Mail 已经被使用, 或格式不正确"));
			}
			
			if (strlen($_POST['password']) < 6 or strlen($_POST['password']) > 16)
			{
				H::ajax_json_output(AWS_APP::RSM(null, - 1, "密码长度不符合规则"));
			}
			
			if ($uid = $this->model('account')->user_register($_POST['user_name'], $_POST['password'], $_POST['email'], true))
			{
				H::ajax_json_output(AWS_APP::RSM(null, 1, "用户添加成功。"));
			}
			else
			{
				H::ajax_json_output(AWS_APP::RSM(null, - 1, "用户添加失败。"));
			}
		
		}
	}

	/**
	 * 设置会员状态
	 * Enter description here ...
	 */
	public function forbidden_status_ajax_action()
	{
		define('IN_AJAX', TRUE);
		
		$user_id = intval($_GET['user_id']);
		
		$user_info = $this->model('account')->get_users_by_uid($user_id);
		
		if ($this->model('account')->update_users_fields(array(
			'forbidden' => !$user_info['forbidden']
		), $user_id))
		{
			H::ajax_json_output(AWS_APP::RSM(null, "1", null));
		}
		else
		{
			H::ajax_json_output(AWS_APP::RSM(null, -1, "系統出錯，请联系管理员"));
		}
	}

	/**
	 * 列出在线列表
	 * Enter description here ...
	 */
	public function online_list_action()
	{
		$per_page = 20;
		
		$page = intval($_GET['page']);
		
		$page = ($page == 0) ? 1 : $page;
		
		$limit = ($page - 1) * $per_page . "," . $per_page;
		
		$page_url = get_setting('base_url') . '/' . G_INDEX_SCRIPT . "/admin/user/online_list/";
		
		//$r_time = time() - (get_setting('online_interval') * 60);
		
		$online_users = $this->model('online')->get_db_online_users(false, null, $limit);
		
		$total_count = $this->model('online')->get_db_online_users(true);
		
		$online_users = $this->online_users_format($online_users);
		
		$this->model('pagination')->initialize(array(
			'base_url' => $page_url, 
			'total_rows' => $total_count, 
			'per_page' => $per_page, 
			'last_link' => '末页', 
			'first_link' => '首页', 
			'next_link' => '下一页 »', 
			'prev_link' => '« 上一页', 
			'anchor_class' => ' class="number"', 
			'cur_tag_open' => '<a class="number current">', 
			'cur_tag_close' => '</a>', 
			'direct_page' => TRUE
		));
		
		TPL::assign('pagination', $this->model('pagination')->create_links());
		TPL::assign('list', $online_users);
		TPL::assign('total_count', $total_count);
		TPL::output('admin/user/online');
	}

	/**
	 * 在线会员列表格式化
	 * Enter description here ...
	 * @param unknown_type $online_users
	 */
	public function online_users_format($online_users)
	{
		if (is_array($online_users))
		{
			foreach ($online_users as $user)
			{
				$uids[] = $user['uid'];
			}
		}
		if (empty($uids))
		{
			return $online_users;
		}
		
		$uids = array_unique($uids);
		
		if ($_user_infos = $this->model('account')->get_users_by_uids($uids))
		{
			$user_infos = array();
			
			foreach ($_user_infos as $user)
			{
				$user_infos[$user['uid']] = $user;
			}
		}
		foreach ($online_users as $key => $val)
		{
			$online_users[$key]['userinfo'] = $user_infos[$val['uid']];
		}
		
		return $online_users;
	}

	public function user_add_action()
	{
		$this->crumb("添加用户", "admin/user/user_add/");
		
		TPL::output('admin/user/add');
	}

}